﻿
$(document).ready(
    function() {
        if (localStorage.length <= 2) {
            $.ajax({
                url: "/Layout/Menu/",
                success: function(data) {
                    var ul = $("<ul class='menu'></ul>");
                    buildMenu(data, data, ul);
                    var menu = $("#menu");
                    ul.appendTo("#menu");
                    saveRoutes(data);
                    var menus = $(".menuItem");
                    $(".menuItem").click(function () {
                        var itemText = this.textContent;
                        var main = $("#mainContent");
                        $("#mainContent").empty();
                        var menuEcq = parseInt(localStorage.getItem(itemText));
                        var url = '/Navigator/Page?numEcq=' + menuEcq;
                        var lload = $("#mainContent").load(url);
                    });
                }
            });
        }

        var writedItems = [];

        var buildMenu = function(source, globalSource, parent) {
            $.each(source, function() {
                var id = this.Id;
                if (writedItems.filter(function(value) {
                    return (value == id);
                }).length == 0) {
                    var curItem = this;
                    var li;
                    li = $("<li>" + curItem.Text + "</li>");
                    li.appendTo(parent);
                    writedItems.push(curItem.Id);
                    var curChilds = globalSource.filter(function(value) {
                        return (value.ParentId == curItem.Id);
                    });
                    if (curChilds.length > 0) {
                        var div = $("<div></div>");
                        div.appendTo(li);
                        var ul = $("<ul></ul>");
                        ul.appendTo(div);
                        buildMenu(curChilds, globalSource, ul);
                    } else {
                        li.addClass("menuItem");
                    }
                }
            });
        
        }

        var saveRoutes = function(data) {
            $.each(data, function() {
                localStorage.setItem(this.Text, this.NumEcq);
            });
        }

    }
);